package day0107

import . "gocode/algorithm/utils"

func mergeKLists(lists []*ListNode) *ListNode {
	var head *ListNode
	for i := 0; i < len(lists); i++ {
		head = mergeTwoLists(head, lists[i])
	}
	return head
}

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	head := &ListNode{}
	tmp := head
	for list1 != nil && list2 != nil {
		if list1.Val > list2.Val {
			tmp.Next = list2
			list2 = list2.Next
		} else {
			tmp.Next = list1
			list1 = list1.Next
		}
		tmp = tmp.Next
	}
	if list1 == nil {
		tmp.Next = list2
	} else if list2 == nil {
		tmp.Next = list1
	}
	return head.Next
}
